import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/auth',
      name: 'Auth',
      component: () => import('@/views/Auth.vue'),
      meta: { requiresGuest: true }
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: () => import('@/views/Dashboard.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/algorithms',
      name: 'Algorithms',
      component: () => import('@/views/Algorithms.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/algorithms/:id',
      name: 'AlgorithmDetail',
      component: () => import('@/views/AlgorithmDetail.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/todos',
      name: 'Todos',
      component: () => import('@/views/Todos.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/calendar',
      name: 'Calendar',
      component: () => import('@/views/Calendar.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: () => import('@/views/Profile.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/fullscreen-demo',
      name: 'FullscreenDemo',
      component: () => import('@/views/FullscreenDemo.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const authStore = useAuthStore()
  
  // 检查认证状态
  if (!authStore.isAuthenticated && authStore.accessToken) {
    try {
      await authStore.verifyToken()
    } catch (error) {
      console.error('Token validation failed:', error)
      authStore.logout()
    }
  }
  
  // 需要认证的路由
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'Auth' })
    return
  }
  
  // 需要游客状态的路由（如登录页）
  if (to.meta.requiresGuest && authStore.isAuthenticated) {
    next({ name: 'Dashboard' })
    return
  }
  
  next()
})

export default router